package cn.tedu.boot61.controller;

import cn.tedu.boot61.mapper.UserMapper;
import cn.tedu.boot61.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(User user) {
        //查询是否存在
        User u = mapper.selectByUsername(user.getUsername());
        if (u == null) {//如果不存在 则可以注册
            mapper.insert(user);
            return 1;//注册成功
        }
        return 2;//用户名已存在
    }

    @RequestMapping("/login")
    public int login(User user, HttpSession session) {
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null) {
            if (u.getPassword().equals(user.getPassword())) {
                //把当前登录成功的用户信息保存到Session会话对象中
                session.setAttribute("u",u);


                return 1;//登陆成功
            } else {
                return 3;//密码错误
            }
        }
        return 2;//用户名不存在
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        //从Session对象中取出当前登录的用户对象并返回给客户端
        return (User) session.getAttribute("u");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除登录成功时候保存的对象
        session.removeAttribute("u");
    }
}
